package com.voicechat.firstmet.utils;

import android.media.MediaRecorder;
import android.os.Handler;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.utils
 * @ClassName: AudioRecorderUtil
 * @Description: 录制语音utils
 * @Author: ljp
 * @CreateDate: 2018/9/19 14:17
 * @Version: 1.0
 */
public class AudioRecorderUtil {
    private final String TAG = AudioRecorderUtil.class.getName();
    public static final int MAX_LENGTH = 60000;
    private String filePath;
    private String fileVoicePath;
    private String folderPath;
    private MediaRecorder mMediaRecorder;
    private int maxLength;
    private long startTime;
    private long endTime;
    private AudioRecorderUtil.OnAudioStatusUpdateListener audioStatusUpdateListener;
    private final Handler mHandler = new Handler();
    private String newVoice;
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            AudioRecorderUtil.this.updateMicStatus();
        }
    };
    private int BASE = 1;
    private int SPACE = 100;

    public AudioRecorderUtil(String folderPath) {
        File path = new File(folderPath);
        if(!path.exists()) {
            path.mkdirs();
        }
        this.folderPath = folderPath;
        this.maxLength = '\uea60';
    }

    public void start(String path) {
        if(this.mMediaRecorder == null) {
            this.mMediaRecorder = new MediaRecorder();
        } else {
            try {
                this.mMediaRecorder.stop();
                this.mMediaRecorder.reset();
                this.mMediaRecorder.release();
            } catch (Exception var2) {
                this.mMediaRecorder.reset();
            }
        }
        this.mHandler.removeCallbacks(this.mUpdateMicStatusTimer);

        try {
          /*  this.mMediaRecorder.setAudioSource(1);
            this.mMediaRecorder.setOutputFormat(0);
            this.mMediaRecorder.setAudioEncoder(1);*/
            //语音介绍保存位置
            this.filePath = this.folderPath + path;
            //如果该路径存在录音文件，就生成新的文件
            if (FileUtils.isExists(filePath)) {
                newVoice = this.folderPath + File.separator  + "newVoice.aac";;
                this.mMediaRecorder.setOutputFile(this.newVoice);
            }else {
                this.mMediaRecorder.setOutputFile(this.filePath);
            }
            this.mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            this.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
            this.mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            this.mMediaRecorder.setMaxDuration(maxLength);
            this.mMediaRecorder.setAudioSamplingRate(8000);

            this.mMediaRecorder.prepare();
            this.mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
                public void onInfo(MediaRecorder mr, int what, int extra) {
                    if(what == 800) {
                        AudioRecorderUtil.this.stop();
                    }
                }
            });
            this.mMediaRecorder.start();
            this.startTime = System.currentTimeMillis();
            this.updateMicStatus();
            if(this.audioStatusUpdateListener != null) {
                this.audioStatusUpdateListener.onStart();
            }
        } catch (IllegalStateException var3) {
            if(this.audioStatusUpdateListener != null) {
                this.audioStatusUpdateListener.onError(var3);
            }

            this.cancel();
        } catch (IOException var4) {
            if(this.audioStatusUpdateListener != null) {
                this.audioStatusUpdateListener.onError(var4);
            }

            this.cancel();
        }

    }
    /**
     * 获取录音文件地址
     */
    public String getFilePath(){
        return this.fileVoicePath;
    }
    /**
    * @method
    * @description 获取录音时间
    * @date: 2018/11/27 16:12
    * @author: ljp
    * @return
    */
    public long getSumTime() {
        return this.startTime == 0L?0L:System.currentTimeMillis() - this.startTime;
    }
    public long stop() {
        if(this.mMediaRecorder == null) {
            return 0L;
        } else {
            this.endTime = System.currentTimeMillis();
            try {
                this.mMediaRecorder.stop();
                this.mMediaRecorder.reset();
                this.mMediaRecorder.release();
                this.mMediaRecorder = null;
                if (!TextUtils.isEmpty(newVoice) && FileUtils.isExists(newVoice)){
                    FileUtils.delete(filePath);
                    FileUtils.renameFile(newVoice,filePath);
                }
                if(this.audioStatusUpdateListener != null) {
                    this.audioStatusUpdateListener.onStop(this.filePath);
                    fileVoicePath = this.filePath;
                }
            } catch (RuntimeException var3) {
                this.mMediaRecorder.reset();
                this.mMediaRecorder.release();
                this.mMediaRecorder = null;

                    File file = new File(this.filePath);
                    if(file.exists()) {
                        file.delete();
                    }
                if(this.audioStatusUpdateListener != null) {
                    this.audioStatusUpdateListener.onError(var3);
                }
            }

            this.filePath = "";
            return this.endTime - this.startTime;
        }
    }

    public void cancel() {
        try {
            this.mMediaRecorder.stop();
            this.mMediaRecorder.reset();
            this.mMediaRecorder.release();
            this.mMediaRecorder = null;
        } catch (RuntimeException var2) {
            this.mMediaRecorder.reset();
            this.mMediaRecorder.release();
            this.mMediaRecorder = null;
        }
        /*if (FileUtils.isExists(newVoice)){
            FileUtils.delete(filePath);
            FileUtils.renameFile(newVoice,filePath);
        }else {*/
            if(!TextUtils.isEmpty(newVoice) ) {
                if( FileUtils.isExists(newVoice)){
                    FileUtils.delete(newVoice);
                }
            }
        //}
        this.filePath = "";
        if(this.audioStatusUpdateListener != null) {
            this.audioStatusUpdateListener.onCancel();
        }

    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    private void updateMicStatus() {
        if(this.mMediaRecorder != null) {
            double ratio = (double)this.mMediaRecorder.getMaxAmplitude() / (double)this.BASE;
            double db = 0.0D;
            if(ratio > 1.0D) {
                db = 20.0D * Math.log10(ratio);
                if(null != this.audioStatusUpdateListener) {
                    this.audioStatusUpdateListener.onProgress(db, System.currentTimeMillis() - this.startTime);
                }
            }

            this.mHandler.postDelayed(this.mUpdateMicStatusTimer, (long)this.SPACE);
        }

    }

    public void setOnAudioStatusUpdateListener(AudioRecorderUtil.OnAudioStatusUpdateListener audioStatusUpdateListener) {
        this.audioStatusUpdateListener = audioStatusUpdateListener;
    }

    public interface OnAudioStatusUpdateListener {
        void onStart();

        void onProgress(double var1, long var3);

        void onError(Exception var1);

        void onCancel();

        void onStop(String var1);
    }
}
